// pages/main/index.js

import WeCropper from '../../components/we-cropper/we-cropper.js'
import {Base64Encrypt,Base64Decrypt,Decrypt,EncryptAES,SHA256,RSA_encrypt,RSA} from '../../utils/crypto_RSA_AES'
const device = wx.getSystemInfoSync()
const width = 375
const height =503


let app = getApp();
const HttpAjax = getApp().getHttpData;
import Dialog from '../../components/dist/dialog/dialog';
import Toast from '../../components/dist/toast/toast';

Page({
  data: {
    cropperOpt: {
      id: 'cropper',
      targetId: 'targetCropper',
      pixelRatio: device.pixelRatio,
      width: 375,
      height: 503,
      scale: 2.5,
      zoom: 8,
      cut: {
        x: (width - 320) / 2,
        y: (height - 440) / 2,
        width: 320,
        height: 440
      },
      boundStyle: {
        color: '#04b00f',
        mask: 'rgba(0,0,0,0.8)',
        lineWidth: 1
      }
    },
    ALLdata: [],
    ishaspep: false,
    image: '../../image/write.png',
    imageChange: false,
    show: false,
    PeopleID: '',
    DeptName: '',
    PName: '',
    PCode: '',
    CardData: '',
    IdentityCard: '',
    MobilePhone: '',
    PPassword: '',
    cWidth: 0,
    cHeight: 0,
    istzshow:false
  },
  onLoad: function (options) {
    
    // 页面初始化 options为页面跳转所带来的参数
    this.getData();
    let that = this;
    const {
      cropperOpt
    } = that.data

    cropperOpt.boundStyle.color = '#04b00f'

    that.setData({
      cropperOpt
    })
    console.log(that.data.image)
    if (that.data.image) {
      cropperOpt.src = that.data.image
      that.cropper = new WeCropper(cropperOpt)
        .on('ready', (ctx) => {
          console.log(`wecropper is ready for work!`)
        })
        .on('beforeImageLoad', (ctx) => {
          console.log(`before picture loaded, i can do something`)
          wx.showToast({
            title: '上传中',
            icon: 'loading',
            duration: 20000
          })
          console.log(`current canvas context:`, ctx)
        })
        .on('imageLoad', (ctx) => {
          console.log(`picture loaded`)
          console.log(`current canvas context:`, ctx)
          wx.hideToast()
        })
        .on('beforeDraw', (ctx, instance) => {
          console.log(`before canvas draw,i can do something`)
          console.log(`current canvas context:`, ctx)
        })
    }

  },

  onShow: function () {
    // 页面显示
    
  },


  addcard() {
    wx.navigateTo({
      url: './addcard/index',
    })
  },
  cellClick() { },
  //删除单个
  delclick(e) {
    let cid = e.target.dataset.cid;
    let cn = e.target.dataset.cn;
    let that = this;
    Dialog.confirm({
      title: '提示',
      message: `你要删除账套 ${cn} ？`
    }).then(() => {
      // on confirm

      HttpAjax(app.globalData.url + '/Door/DeleteCustomer', {
        CustomerID: cid
      }, 'post', app.globalData.headerCookie)
        .then(ress => {
          let res = ress.data;
          if (res.result) {
            Toast(`${cn}已删除`);

            that.getData();
          } else {
            Toast(`${cn}删除失败`);
          }
          setTimeout(()=>{
            Toast.clear();
          },2000)
        })
        .catch(err => {
          console.error(err)
        })


    }).catch(() => {
      // on cancel
      console.log(123)
    });
  },
  getData(parma = {}) {
    let that = this;
    Toast.loading({
      mask: true,
      message: '数据加载中'
    });
    HttpAjax(app.globalData.url + '/Door/GetCustomerList', parma, 'post', app.globalData.headerCookie)
      .then(ress => {
        setTimeout(() => {
          Toast.clear();
        }, 2000)
        let res = ress.data;

        if (res.result == 1) {
          that.setData({
            istzshow: true
          })
          if (res.customerlist.length == 0) {
            // that.data.ishaspep==true;
            that.setData({
              ishaspep: false
            })
          } else {
            let customerlist = res.customerlist[0];
            console.log(customerlist.PPassword,Base64Decrypt(customerlist.PPassword,wx.getStorageSync('AKey'),wx.getStorageSync('AIV')));
            that.setData({
              ishaspep: true,
              PeopleID: customerlist.PeopleID,
              DeptName: customerlist.DeptName,
              PName: customerlist.PName,
              PCode: customerlist.PCode,
              CardData: customerlist.CardData,
              IdentityCard: customerlist.IDCode,
              MobilePhone: customerlist.MobilePhone,
              PPassword: Base64Decrypt(customerlist.PPassword,wx.getStorageSync('AKey'),wx.getStorageSync('AIV')),
              image: customerlist.PImage ? 'https://yun.pc15.net/OSSImage_FCARD/' + customerlist.PImage + '?'+Math.ceil(Math.random() * 100):'../../image/write.png',
            })
            
          }
          that.setData({
            ALLdata: res.customerlist
          })
        }else{
          that.setData({
            istzshow: true
          })
        }
      }).catch(err => {
        that.setData({
          istzshow: true
        })
        setTimeout(() => {
          Toast.clear();
        }, 2000)
      })
  },
  upload() {
    console.log(13213);
    // this.cropper.pushOrign(this.data.image)
    this.setData({
      show: true
    });
    console.log(this.data.image)
    this.cropper.pushOrign(this.data.image)
  },
  cancel() {
    this.setData({
      show: false
    });
  },
  touchStart(e) {
    this.cropper.touchStart(e)
  },
  touchMove(e) {
    this.cropper.touchMove(e)
  },
  touchEnd(e) {
    this.cropper.touchEnd(e)
  },
  getCropperImage() {
    this.cropper.getCropperImage({
      quality: .1,
    }, (path, err) => {
      console.log(path, err)
      if (err) {
        wx.showModal({
          title: '温馨提示',
          content: err.message
        })
      } else {
        this.setData({
          image: path,
          show: false,
          imageChange: true
        })


      }
    })
  },
  uploadTap() {
    const self = this

    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) {
        const src = res.tempFilePaths[0]
        //  获取裁剪图片资源后，给data添加src属性及其值

        self.cropper.pushOrign(src)
      }
    })
  },
  OnChange(e) {
    console.log(e.currentTarget.dataset.name);
    let json = {};
    json[e.currentTarget.dataset.name] = e.detail;
    console.log(json)
    this.setData(json)
  },
  toPerson() {
    let CustomerName = this.data.ALLdata[0].CName;
    let UserPassWord = this.data.PPassword;
    let UserName, authMode;
    let arr = ['MobilePhone', 'CardData', 'IdentityCard'];
    for (let i = 0; i < arr.length; i++) {
      if (this.data[arr[i]]) {
        UserName = this.data[arr[i]];
        authMode = arr.length - i;
        break;
      }
    }
    console.log(`../WebView/index?CustomerName=${CustomerName}&UserName=${UserName}&UserPassWord=${UserPassWord}&authMode=${authMode}`)
    // return;

    wx.navigateTo({
      url: `../WebView/index?CustomerName=${CustomerName}&UserName=${UserName}&UserPassWord=${UserPassWord}&authMode=${authMode}`
    })
  },
  updataPerson() {
    if (!(/^1[3|5|7|8][0-9]\d{4,8}$/.test(this.data.MobilePhone))) {
      Toast(`手机号码格式不正确`);
      setTimeout(() => {
        Toast.clear();
      }, 2000)
      return
    }
    if (this.data.PPassword == '') {
      Toast(`密码不能为空`);
      setTimeout(() => {
        Toast.clear();
      }, 2000)
      return
    }
    console.log('updataPerson')
    let that = this;
    let parma = {
      pID: this.data.PeopleID,
      DeptName: this.data.DeptName,
      PName: this.data.PName,
      PCode: this.data.PCode,
      CardData: this.data.CardData,
      IdentityCard: this.data.IdentityCard,
      MobilePhone: this.data.MobilePhone,
      PPassword: Base64Encrypt(this.data.PPassword,wx.getStorageSync('AKey'),wx.getStorageSync('AIV'))
    }
    HttpAjax(app.globalData.url + '/Door/Update', parma, 'post', app.globalData.headerCookie).then(res => {
      // console.log(res)
      Toast(`更新信息成功`);
      setTimeout(() => {
        Toast.clear();
      }, 2000)
    })
    if (this.data.imageChange) {

      this.cutImage(that.data.image).then(res => {
        console.log(res)
        wx.getFileSystemManager().readFile({
          filePath: res.tempFilePath, //选择图片返回的相对路径
          encoding: 'base64', //编码格式
          success: res => {
            console.log(res)
            let base64Url = wx.arrayBufferToBase64(res.data);
            const imgdata = 'data:image/' + 'JPG' + ';base64,' + res.data;
            HttpAjax(app.globalData.url + '/door/Upload', {
              base64: imgdata
            }, 'post', app.globalData.headerCookie).then(res => {
              console.log(res)
              that.setData({
                imageChange: false
              })
              if (res.data.result==0){
                Toast('图像更新失败，请上传个人人脸照！');
                setTimeout(() => {
                  Toast.clear();
                }, 2000)
              }
            })
          },
          fail: res => {
            console.log(res)
          }
        })
      }).catch(err => {
        console.log(err)
      })
    }



  },
  cutImage(imgsrc) {
    console.log(imgsrc)
    let that = this;
    let p = new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: imgsrc,
        success: function (res) {
          //---------利用canvas压缩图片--------------
          var ratio = 1;
          console.log(res)
          var canvasWidth = res.width //图片原始长宽
          var canvasHeight = res.height
          while (canvasWidth > 400 || canvasHeight > 440) { // 保证宽高在400以内
            canvasWidth = 320
            canvasHeight = 440
            ratio++;
          }
          that.setData({
            cWidth: canvasWidth,
            cHeight: canvasHeight
          })

          //----------绘制图形并取出图片路径--------------
          var ctx = wx.createCanvasContext('canvas')
          ctx.drawImage(res.path, 0, 0, canvasWidth, canvasHeight)
          ctx.draw(false, setTimeout(function () {
            wx.canvasToTempFilePath({
              x: 0,
              y: 0,
              // width:160,
              // height:220,
              canvasId: 'canvas',
              destWidth: 320,
              destHeight: 440,
              quality:0,
              fileType:'png',
              success: function (res) {
                console.log(res.tempFilePath) //最终图片路径
                resolve(res)
              },
              fail: function (res) {
                console.log(res.errMsg)
                reject(res)
              }
            })
          }, 100))
        },
        fail: function (res) {
          reject(res)
          console.log(res.errMsg)
        }
      })
    })
    return p;
  },
  refresh(){
    this.onLoad()
  }
})